#include "fileOperations.h"
#include "basic.h"
#include <stdio.h>

/**
 * Handles file operations: saving, reading, and writing
 */


/* Reads a file to a buffer.
 * 
 * @param buff - The buffer to read file into.
 * @param fileToRead - Name of file to read.
 * @return - 0:fail, 1:content size.
 */

int readFile(char * buff, char * fileToRead) {

	int cntSize = 0;
	FILE *freadp;
	if ((freadp	= fopen (fileToRead, "rb")) == NULL) {
		error("readFile1");
	}
	else { //open file to read
	
		if (freadp != NULL) {
		
			if ((cntSize = fread (buff, 1, MAX_MSG, freadp)) == 0) {
				error("readFile2");
			}
			if (ferror(freadp)) {
				printf("error freadp");
			}
			if (debug) {
				printf("Displaying content of %s: ", fileToRead);
			}
		
			//fputs (buff, stdout);
		
			if (debug) {
				printf ("\nDONE...Content size of %s is %d bytes.\n",fileToRead, cntSize);
			}
		
			fclose (freadp);
		}
		else {
			perror ( "readFile3" ); //display any error 	
		}
	}
		return cntSize;
}

/* Writes from a buffer into a file.
 * 
 * @param buff - The buffer to read the file into.
 * @param bufferSize - The size of the buffer / size of the content.
 * @param fileToRead - Name of the file to read from.
 * @return - 1:succesful , 0:unsucessful
 */
int writeToFile(char * buff, int bufferSize, char * fileToWrite){
	
	int flag = 0;
	FILE *fwritep = fopen ( fileToWrite, "wb" ); //open file to write/append
	
	if (bufferSize != 0 || buff != NULL || fwritep != NULL){
		
		if (debug) {
			printf("Writing content of buffer into %s. . .\n", fileToWrite);
		}
		
	fwrite(buff, 1, bufferSize, fwritep);
	//fputs(buff, fwritep);
		if (debug) {
			printf ("Done writing. Content size of %s is %d bytes.\n", fileToWrite, bufferSize);
		}
		fclose (fwritep);
		flag = 1;	
	} 
	else {
		perror( "writeFile" );
	}
	
	return flag;
}